import Taro from '@tarojs/taro';
import {Image, View, Text} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {request, unite} from '../../../utils/index';
import './mealList.scss';
import Close from "../../../asset/images/close.png";
import PhoneModal from "../../../components/phone-modal/phoneModal";
import {actionCreator} from "../../../store/actions";

class MealList extends Taro.Component {
    config = {
        navigationBarTitleText: '套餐',
        navigationBarBackgroundColor: '#ffffff'
    };

    state = {
        mealStatus: false,
        couponList: [],
        phoneId: false, // 0 未授权手机号
        phoneStatus: true, //授权弹窗 手机号1
        packageId: null, //选中的ID
    };

    componentDidMount() {
        this.getCoupon(); //获取套餐列表
    }

    //获取套餐列表
    getCoupon = () => {
        const option = this.$router.params;
        console.log(option.phoneId +'option.phoneId');
        const params = {
            url: '/wx/packages/listPackages',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            couponList: res.data,
                            phoneId: Number(option.phoneId),
                            packageId: option.packageId || null,  //选中的Id
                        });
                        if (option.packageId) {
                            res.data.forEach((item) => {
                                if (option.packageId == item.packageId) {
                                    this.paySetMeal(item);
                                    this.paySetMealBoy();
                                }
                            });
                        }
                    }
                }
            }
        })
    };

    //购买套餐
    paySetMeal = (item) => {
        this.setState(prevState => ({
            mealData: item ? item : [],
            packageId: item.packageId,
        }))
    };

    paySetMealBoy = () => {
        this.setState(prevState => ({
            mealStatus: !prevState.mealStatus
        }))
    };

    //微信支付购买套餐
    sumbit = () => {
        const {mealData} = this.state;
        const {mobileFlag} = this.props;
        if (mobileFlag != 0) { //授权手机号
            const params = {
                url: '/wx/packages/pay',
                data:{
                    packageId: mealData.packageId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        if (res) {
                            this.onMiniPay(res);
                        }
                    }
                }
            })
        } else { //未授权手机号
            this.setState({
                phoneStatus: false,
            })
        }
        this.setState({
            mealStatus: false,
        })
    };

    //授权手机号
    unGetPhone = (is) => {
        const {userData} = this.state;
        const {setMobileFlag} = this.props;
        this.setState({
            phoneStatus: true,
            phoneId: is == 1 ? true : false, //关闭弹窗
        }, () => {
            if (is) {
                setMobileFlag(1);
                this.sumbit();
            }
        });
    };

    //小程序支付
    onMiniPay = info => {
        Taro.requestPayment({
            timeStamp: info.data.timeStamp.toString(),
            nonceStr: info.data.nonceStr,
            package: info.data.packageValue,
            signType: info.data.signType,
            paySign: info.data.paySign,
            success: () => {
                unite.showToast('购买成功');
            },
            fail: () => {
                unite.showToast('支付失败');
                console.log('支付失败');
            },
        });
    };

    render() {
        const {mealStatus, couponList, mealData, phoneStatus, packageId} = this.state;
        return (
            <View className="meal-list-contents">
                <View className="meal-list-content">
                    {couponList && couponList.map((item, index) => (
                        <View className={`yhq-item flex-bottom ${item.packageId == packageId ? 'yhq-item-in' : ''}`} key={index} onClick={this.paySetMeal.bind(this, item)}>
                            <View className="item-left-text">
                                <View className="flex-l price">
                                    <View className="price-nums">¥{item.factAcceptCharge}</View>
                                    <View>（到账¥{item.chargeTotal}）</View>
                                </View>
                                <View>{item.couponDesc}</View>
                            </View>
                            <View className="titles">{item.description}</View>
                            <View className="set-meal flex-center">套餐</View>
                        </View>
                    ))}
                </View>
                <View className="meal-botttom-content">
                    <View className="meal-text">购买须知</View>
                    <View className="meal-title">1.购买须知购买须知购买须知购买须知</View>
                    <View className="meal-title">2.购买须知购买须知购买须知购买须知购买须知</View>
                    <View className="sumbit-btn-wrap">
                        <View className="sum-text">7天无条件退款，余额可补差价使用</View>
                        <View className="sumbit-btn flex-center" onClick={this.paySetMealBoy}>微信支付</View>
                    </View>
                </View>
                {/*    购买套餐弹窗*/}
                {mealStatus && (
                    <View className="model-type flex-bottom">
                        <View className="set-meal-content">
                            <View className="meal-names">
                                <View>购买套餐</View>
                                <Image className="img-close" src={Close} onClick={this.paySetMealBoy} mode="aspectFit"/>
                            </View>
                            <View className="meal-list-wrap">
                                <View className="meal-list flex-lr">
                                    <View>套餐名称</View>
                                    <View className="name">{mealData.packageName}</View>
                                </View>
                                <View className="meal-list flex-lr">
                                    <View>到账</View>
                                    <View className="name">{mealData.chargeTotal}元</View>
                                </View>
                                <View className="meal-list meal-list-none flex-lr">
                                    <View>优惠券</View>
                                    <View className="name">{mealData.couponDesc}</View>
                                </View>
                            </View>
                            <View className="prompt-text">7天无条件退款，余额可补差价使用</View>
                            <View className="max-btn flex-center" onClick={this.sumbit}>微信支付 ¥{mealData.factAcceptCharge}</View>
                        </View>
                    </View>
                )}
                {!phoneStatus &&(
                    <PhoneModal onCancel={this.unGetPhone}/>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {mobileFlag} = state;
    return {
        mobileFlag
    }
};

const mapDispatchToProps = {
    setMobileFlag: actionCreator.setMobileFlag,
};

export default connect(mapStateToProps, mapDispatchToProps)(MealList);



